package leo.peersim.paxos;

import java.util.Random;

import leo.peersim.common.MessageTrigger;

import org.apache.log4j.Logger;

import peersim.config.Configuration;
import peersim.core.CommonState;
import peersim.core.Control;
import peersim.core.Network;
import peersim.core.Node;
import peersim.edsim.EDSimulator;

public class ChurnTrigger implements Control {
	
	private static Logger logger = Logger.getLogger(MessageTrigger.class.getName());
		
		private final int protocolID;
		
		private int sequenceNumber = 0;
		
		private int _load; //operations/sec
		private int _churnRate;
		
		private final int _loadingInterval = 10000; //milliseconds
		private long numberOfRequestToBeIssued;
		
		public ChurnTrigger(String prefix) {
			this.protocolID = Configuration.getPid(prefix + "." + "protocol");
			this._load = Configuration.getInt(prefix + "." + "load");
			
			this.numberOfRequestToBeIssued = (long) Math.ceil( (this._loadingInterval/1000) * this._load );
		}

		/**
		 * <p>Load the fault tolerant FSA with an amount of operations/s as
		 * specified by the load value in the configuration file.</p>
		 */
		@Override
		public boolean execute() {
			Random r = new Random();
			
			Node leaderNode = Network.get(0);
			
			for(int i=0; i<numberOfRequestToBeIssued; i++) {
				
				String command = "C" + (this.sequenceNumber++);
				
				int delay = r.nextInt(_loadingInterval);
				logger.debug(CommonState.getTime() + "\ttriggering request _" + command + "_ to agent[" + leaderNode.getID() + "] @ time " + delay + "...");
				
				ClientRequest request = new ClientRequest(command, delay);
				EDSimulator.add(delay, request, leaderNode, this.protocolID);
			}
			return false;
		}
	}
